﻿using Basic.Infra.Core.Custom;
using Newtonsoft.Json;

namespace Basic.Base.System.Extensions.Dictionary;

public static class DictionaryExtentions
{
    public static Dictionary<string, object> CreateDictFromJson(this string json)
    {
        //var dictionary = JsonSerializer.Deserialize<Dictionary<string,object>>(json, SystemTextJson.GetDefaultOptions());
        var dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
        return dictionary;
    }
    public static Dictionary<string, object> CreateDictionaryFromObject(this object obj)
    {
        Dictionary<string, object> dictionary = new Dictionary<string, object>();
        PropertyInfo[] properties = obj.GetType().GetProperties();

        foreach (PropertyInfo property in properties)
        {
            object value = property.GetValue(obj, null);
            if (value is not null)
                dictionary[property.Name] = value;
        }

        return dictionary;
    }
    public static T ConvertToObject<T>(IDictionary<string, object> dictionary) where T : new()
    {
        Type type = typeof(T);
        PropertyInfo[] properties = type.GetProperties();

        T result = Activator.CreateInstance<T>();

        foreach (var property in properties)
        {
            if (dictionary.ContainsKey(property.Name))
                property.SetValue(result, dictionary[property.Name]);
        }
        return result;
    }
}
